package com.koron.plan.web.repairplan.filter;

import com.alibaba.fastjson.JSON;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.org.dto.OrgDto;
import com.koron.bean.system.post.query.PostUserQuery;
import com.koron.bean.system.post.vo.PostUserVo;
import com.koron.bean.workflow.SubmitterParam;
import com.koron.bean.workflow.WorkflowUser;
import com.koron.common.core.business.system.feign.SystemFeignService;
import com.koron.common.core.util.CommonUtils;
import com.koron.plan.web.repairplan.bean.vo.PlanPackageIssueVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author twcao
 * @title: MaintainPackageFilter
 * @projectName GDH_EAM_V2
 * @description: 检修计划的过滤规则
 * @date 2022/1/1015:19
 */
@Slf4j
@Component
public class RepairPlanFilter {

    @Autowired
    private SystemFeignService systemFeignService;

    /**
     处理节点：创建单位负责人审批
     自动过滤规则：自动发送至创建单位的主任、站长
     处理人：主任（岗位）、站长（岗位）
     组织从业务数据中获取，此处配置的组织无效
     * @param factory
     * @param submitterParam
     * @return
     */
    @TaskAnnotation("task0Submitter")
    public List<WorkflowUser> task0Submitter(SessionFactory factory, SubmitterParam submitterParam) {
        PlanPackageIssueVO vo = JSON.parseObject(submitterParam.getFormVariables(),  PlanPackageIssueVO.class);
        // 创建人所在组织id
        String orgId = vo.getOrgId();
        List<WorkflowUser> users = filter(factory, account(submitterParam), postCode(submitterParam), Arrays.asList(orgId));
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        log.info("检修计划[task0Submitter]设置审批人结果: {}", JSON.toJSONString(users));
        return users;
    }

    /**
     处理节点：创建部门负责人审批
     自动过滤规则：自动发送到创建人所在部门的部门总经理
     处理人：部门总经理（岗位）
     组织从业务数据中获取，此处配置的组织无效
     * @param factory
     * @param submitterParam
     * @return
     */
    @TaskAnnotation("task2Submitter")
    public List<WorkflowUser> task2Submitter(SessionFactory factory, SubmitterParam submitterParam) {
        PlanPackageIssueVO vo = JSON.parseObject(submitterParam.getFormVariables(),  PlanPackageIssueVO.class);
        // 创建人所在部门
        List<String> deptIds = getDeptIdByOrgId(Arrays.asList(vo.getOrgId()));
        List<WorkflowUser> users = filter(factory, account(submitterParam), postCode(submitterParam), deptIds);
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        log.info("检修计划[task2Submitter]设置审批人结果: {}", JSON.toJSONString(users));
        return users;
    }

    /**
     处理节点：技术部负责人审批
     自动过滤规则：自动发送到生产技术部的部门总经理
     处理人：部门总经理（岗位），由插件配置，这里读取即可
     组织：生产技术部，由插件配置，这里读取即可
     * @param factory
     * @param submitterParam
     * @return
     */
    @TaskAnnotation("task4Submitter")
    public List<WorkflowUser> task4Submitter(SessionFactory factory, SubmitterParam submitterParam) {
        List<WorkflowUser> users = filter(factory, account(submitterParam), postCode(submitterParam), orgs(submitterParam));
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        log.info("检修计划[task0Submitter]设置审批人结果: {}", JSON.toJSONString(users));
        return users;
    }

    @TaskAnnotation("task2Handler")
    public List<WorkflowUser> task2Handler(SessionFactory factory, SubmitterParam submitterParam) {
        List<WorkflowUser> users = filter(factory, account(submitterParam), postCode(submitterParam), orgs(submitterParam));
        log.info("检修计划[task2Handler]人员过滤: {}", JSON.toJSONString(users));
        return users;
    }

    @TaskAnnotation("task4Handler")
    public List<WorkflowUser> task4Handler(SessionFactory factory, SubmitterParam submitterParam) {
        List<WorkflowUser> users = filter(factory, account(submitterParam), postCode(submitterParam), orgs(submitterParam));
        log.info("检修计划[task4Handler]人员过滤: {}", JSON.toJSONString(users));
        return users;
    }

    /**
     * 获取岗位
     * @param submitterParam
     * @return
     */
    private List<String> postCode(SubmitterParam submitterParam) {
        List<WorkflowUser> users = submitterParam.getUsers();
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        // 岗位编码
        List<String> postCodes = users.stream().filter(row -> row.getType() == 2).map(WorkflowUser::getCode).collect(Collectors.toList());
        return postCodes;
    }

    /**
     * 人员
     * @param submitterParam
     * @return
     */
    private List<String> account(SubmitterParam submitterParam) {
        List<WorkflowUser> users = submitterParam.getUsers();
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        // 人员账号
        List<String> userAccounts = users.stream().filter(row -> row.getType() == 0).map(WorkflowUser::getCode).collect(Collectors.toList());
        return userAccounts;
    }

    /**
     * 组织
     * @param submitterParam
     * @return
     */
    private List<String> orgs(SubmitterParam submitterParam) {
        List<WorkflowUser> users = submitterParam.getUsers();
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        // 人员组织
        List<String> orgs = users.stream().filter(row -> row.getType() == 1).map(WorkflowUser::getCode).collect(Collectors.toList());
        return orgs;
    }

    /**
     * 根据岗位和组织查询审批人
     * 人员列表 && 组织列表 && 岗位列表
     * @param factory 会话
     * @param accounts 人员列表
     * @param orgList 组织列表
     * @param postCodes 岗位列表
     * @return
     */
    private List<WorkflowUser> filter(SessionFactory factory, List<String> accounts, List<String> postCodes, List<String> orgList) {
        if(CollectionUtils.isEmpty(postCodes) && CollectionUtils.isEmpty(orgList)) {
            return null;
        }
        PostUserQuery query = new PostUserQuery();
        query.setPostIdList(postCodes);
        query.setOrgIdList(orgList);
        List<PostUserVo> vos = CommonUtils.ok(systemFeignService.queryPostList(query));
        List<WorkflowUser> users = new ArrayList<>();
        vos.stream().forEach(vo -> {
            WorkflowUser user = new WorkflowUser();
            if(!CollectionUtils.isEmpty(accounts) && !accounts.contains(user.getCode())) {
                return;
            }
            user.setCode(vo.getUserAccount());
            user.setName(vo.getUserName());
            users.add(user);
        });
        if (users.size() == 0) {
            return null;
        }
        return users;
    }

    private List<String> getDeptIdByOrgId(List<String> orgIds) {
        OrgDto orgDto = new OrgDto();
        orgDto.setOrgIds(orgIds);
        List<OrgBean> depts = CommonUtils.ok(systemFeignService.queryDeptByOrgIdList(orgDto));
        return depts.stream().map(OrgBean::getDeptId).collect(Collectors.toList());
    }
}
